<?php
function mergeSortedFiles($inputFile, $tempDir, $maxLines = 10000)
{
    $handle = fopen($inputFile, 'r');
    $lines = [];

    $tempPath = $tempDir . '/temp';
    if (!is_dir($tempPath)) {
        mkdir($tempPath, 0755, true);
    }

    while (($line = fgets($handle)) !== false) {
        $lines[] = $line;
        if (count($lines) >= $maxLines) {
            sort($lines);
            $tempFile = tempnam($tempPath, 'sorted');
            $tempHandle = fopen($tempFile, 'w');
            fwrite($tempHandle, implode('', $lines));
            $lines = [];
            fclose($tempHandle);
        }
    }

    sort($lines);
    $tempFile = tempnam($tempPath, 'sorted');
    $tempHandle = fopen($tempFile, 'w');
    fwrite($tempHandle, implode('', $lines));
    fclose($tempHandle);
    fclose($handle);

    return $tempPath;
}


// 示例使用
$inputFile = './runtime/large_data.txt'; // 大文件路径
$tempDir = './runtime'; // 临时文件夹路径
$maxLines = 10000; // 每个分块的最大行数

$tempPath = mergeSortedFiles($inputFile, $tempDir, $maxLines);
echo "Sorted file: " . $tempPath . "\n";


function mergeFiles($file1, $file2, $outputFile) {
    $handle1 = fopen($file1, 'r');
    $handle2 = fopen($file2, 'r');
    $handleOut = fopen($outputFile, 'w');

    $line1 = fgets($handle1);
    $line2 = fgets($handle2);

    while ($line1 !== false && $line2 !== false) {
        if ($line1 < $line2) {
            fwrite($handleOut, $line1);
            $line1 = fgets($handle1);
        } else {
            fwrite($handleOut, $line2);
            $line2 = fgets($handle2);
        }
    }

    // 如果第一个文件还有剩余行，写入输出文件
    while ($line1 !== false) {
        fwrite($handleOut, $line1);
        $line1 = fgets($handle1);
    }

    // 如果第二个文件还有剩余行，写入输出文件
    while ($line2 !== false) {
        fwrite($handleOut, $line2);
        $line2 = fgets($handle2);
    }

    fclose($handle1);
    fclose($handle2);
    fclose($handleOut);
}

// 假设我们只有两个文件需要合并
mergeFiles('part_001.txt', 'part_002.txt', 'merged.txt');
// 对于多个文件，你可能需要递归地合并它们，或者使用一个队列来管理要合并的文件
